package com.example.wechat.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.project.entity.User;
import com.example.project.service.CommonService;
import com.example.project.service.impl.BaseServiceImpl;
import com.example.wechat.mapper.WechatConversationMapper;
import com.example.wechat.model.WechatConversation;

/**
 * 聊天会话Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-11-12
 */
@Service
public class WechatConversationService extends BaseServiceImpl {

	@Autowired
	private CommonService commonService;

	@Autowired
	private WechatConversationMapper wechatConversationMapper;

	/**
	 * 查询会话
	 * 
	 * @param userId
	 * @param targetId
	 * @param sessionType
	 * @return
	 */
	public WechatConversation queryConversation(long userId, long targetId, int sessionType) {
		// TODO Auto-generated method stub
		wechatConversationMapper.queryByUserIdAndTargetIdAndSessionType(userId, targetId, sessionType);

		WechatConversation wechatConversation = wechatConversationMapper.queryByUserIdAndTargetIdAndSessionType(userId,
				targetId, sessionType);
		if (wechatConversation == null) {
			User user = getUser();
			// 查询用户信息
			User contactUserInfo = commonService.getUserInfo(targetId);
			if (contactUserInfo == null) {
				return wechatConversation;
			}
			// 创建好友关系
			wechatConversation = this.insert(user, contactUserInfo, sessionType);
			this.insert(contactUserInfo, user, sessionType);
		}
		return wechatConversation;
	}

	public WechatConversation insert(User user, User contactUserInfo, int sessionType) {
		// TODO Auto-generated method stub
		WechatConversation info = new WechatConversation();
		info.setUserId(String.valueOf(user.getUserId()));
		info.setTargetId(String.valueOf(contactUserInfo.getUserId()));
		info.setSessionType(sessionType);
		info.setLastMessageId(0L);
		info.setUnreadCount(0);
		info.setIsPinned(0);
		info.setIsMuted(0);
		wechatConversationMapper.insertWechatConversation(info);
		return info;
	}
}
